"""
uiautomator2 高级自动化脚本
功能：
1. 启动指定应用
2. 智能检测页面状态
3. 支持多种滑动模式
4. 异常处理和自动恢复
"""

import uiautomator2 as u2
import time
import random
import argparse
from datetime import datetime

class VideoAutomation:
    def __init__(self, package_name, interval=5, total_count=None):
        self.package_name = package_name
        self.interval = interval
        self.total_count = total_count
        self.device = None
        self.count = 0
        self.width = 0
        self.height = 0
        
    def connect(self):
        """连接设备并启动应用"""
        try:
            self.device = u2.connect()
            self.width, self.height = self.device.window_size()
            
            print(f"✅ 已连接设备: {self.device.info.get('productName', 'Unknown')}")
            print(f"📱 分辨率: {self.width}x{self.height}")
            return True
            
        except Exception as e:
            print(f"❌ 连接设备失败: {e}")
            return False
    
    def start_app(self):
        """启动应用"""
        try:
            print(f"🚀 正在启动应用: {self.package_name}")
            self.device.app_start(self.package_name)
            time.sleep(3)
            
            current = self.device.app_current()
            if current.get('package') == self.package_name:
                print(f"✅ 应用启动成功")
                return True
            else:
                print(f"⚠️  启动的应用不匹配")
                return False
                
        except Exception as e:
            print(f"❌ 启动应用失败: {e}")
            return False
    
    def check_app_running(self):
        """检查应用是否在前台运行"""
        try:
            current = self.device.app_current()
            return current.get('package') == self.package_name
        except:
            return False
    
    def swipe_up(self):
        """向上滑动"""
        try:
            x = self.width // 2
            y1 = int(self.height * 0.75)
            y2 = int(self.height * 0.25)
            
            self.device.swipe(x, y1, x, y2, 0.3)
            self.count += 1
            return True
            
        except Exception as e:
            print(f"❌ 滑动失败: {e}")
            return False
    
    def random_swipe(self):
        """随机滑动"""
        # 90% 向上，10% 向下
        if random.random() < 0.9:
            return self.swipe_up()
        else:
            x = self.width // 2
            y1 = int(self.height * 0.25)
            y2 = int(self.height * 0.75)
            self.device.swipe(x, y1, x, y2, 0.3)
            print("   ↓ 随机向下")
            return True
    
    def should_continue(self):
        """判断是否继续"""
        if self.total_count is None:
            return True
        return self.count < self.total_count
    
    def get_random_interval(self):
        """获取随机间隔"""
        variation = self.interval * 0.2
        return self.interval + random.uniform(-variation, variation)
    
    def run(self):
        """运行自动化任务"""
        if not self.connect():
            return
        
        if not self.start_app():
            return
        
        print(f"\n⏰ 平均间隔: {self.interval} 秒（随机波动）")
        if self.total_count:
            print(f"🎯 目标次数: {self.total_count} 次")
        else:
            print(f"🔄 持续运行（按 Ctrl+C 停止）")
        print("-" * 50)
        
        start_time = time.time()
        
        try:
            while self.should_continue():
                if not self.check_app_running():
                    print("⚠️  应用不在前台，重新启动...")
                    if not self.start_app():
                        break
                
                timestamp = datetime.now().strftime('%H:%M:%S')
                print(f"[{self.count + 1}] {timestamp} ", end="")
                
                if self.random_swipe():
                    print("✅")
                else:
                    print("❌")
                
                if self.should_continue():
                    wait_time = self.get_random_interval()
                    time.sleep(wait_time)
                    
        except KeyboardInterrupt:
            print("\n\n⏹️  用户停止")
        except Exception as e:
            print(f"\n❌ 发生错误: {e}")
        finally:
            elapsed = time.time() - start_time
            print(f"\n📊 统计:")
            print(f"   - 滑动次数: {self.count}")
            print(f"   - 运行时长: {int(elapsed)} 秒")

def main():
    parser = argparse.ArgumentParser(description='uiautomator2 自动化脚本')
    parser.add_argument('package', help='应用包名')
    parser.add_argument('-i', '--interval', type=float, default=5.0,
                       help='滑动间隔（秒），默认5秒')
    parser.add_argument('-n', '--count', type=int, default=None,
                       help='滑动次数，不指定则无限循环')
    
    args = parser.parse_args()
    
    automation = VideoAutomation(
        package_name=args.package,
        interval=args.interval,
        total_count=args.count
    )
    automation.run()

if __name__ == "__main__":
    main()